package com.leyou.user.service.impl;

import com.leyou.common.enums.LyExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.common.utils.constants.MQConstants;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Boolean checkUsernameAndPhone(String data, Integer type) {
        User u= new User();
       /* if () {
        }else if(){

        }else(){

        }*/
       switch (type){
           case 1:
               u.setUsername(data);
               break;
           case 2:
               u.setPhone(data);
               break;
           default:
               throw new LyException(LyExceptionEnum.INVALID_PARAM_ERROR);
       }

        int count = userMapper.selectCount(u);

        return count==0?true:false;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public void sendCode(String phone) {
        //1、校验手机号
        if(!RegexUtils.isPhone(phone)){
            throw new LyException(LyExceptionEnum.INVALID_PHONE_NUMBER);
        }

        //2、生成随机6位数字验证码
        String smsCode = RandomStringUtils.randomNumeric(6);
        //3、将验证码存入redis  5分钟
        redisTemplate.boundValueOps(phone).set(smsCode,5L, TimeUnit.MINUTES);

        //4、发送短信  将发短信所需要参数 Phone  code 作为参数，生成rabbitmq消息
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",smsCode);
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME,MQConstants.RoutingKey.SMS_KEY,map);

    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    @Override
    public void register(UserDTO userDTO, String code) {
        //1、校验验证码是否有效
        String sysCode = redisTemplate.boundValueOps(userDTO.getPhone()).get();
       /* if (!StringUtils.equals(code,sysCode)) {
            throw new LyException(LyExceptionEnum.INVALID_VERIFY_CODE);
        }*/
        if (sysCode==null) {
            throw new LyException(LyExceptionEnum.INVALID_VERIFY_CODE);
        }
        if (!code.equals(sysCode)) {
            throw new LyException(LyExceptionEnum.INVALID_VERIFY_CODE);
        }

        //2、对密码加密  随机加盐
        User user = BeanHelper.copyProperties(userDTO, User.class);
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);

        //3、将数据保存数据库中
        int count = userMapper.insertSelective(user);
        if(count!=1){
            throw new LyException(LyExceptionEnum.INSERT_OPERATION_FAIL);
        }
        //注册成功后，清除系统验证码


    }
//登录时进行用户名和密码验证
    @Override
    public UserDTO queryUser(String username, String password) {
        User u = new User();
        u.setUsername(username);

        //基于用户名查询用户信息
        User user = userMapper.selectOne(u);
        if(user==null){
            throw new LyException(LyExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //校验用户输入的密码是否有效
        String sysPassword = user.getPassword();
        //参数一：明文密码 参数二：数据库中密文
        //passwordEncoder对象解密,只需要拿明文密码和数据库中的密文进行对比即可(passwordEncoder已经封装好解密方法)
        if (!passwordEncoder.matches(password,sysPassword)) {
            throw new LyException(LyExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        return BeanHelper.copyProperties(user,UserDTO.class);
    }
}
